package com.jagochan.module.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jagochan.common.result.PageVO;
import com.jagochan.module.business.mapper.CommentMapper;
import com.jagochan.module.business.pojo.po.Comment;
import com.jagochan.module.business.pojo.po.User;
import com.jagochan.module.business.pojo.vo.CommentVO;
import com.jagochan.module.business.service.CommentService;
import com.jagochan.module.business.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;


@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Resource
    private UserService userService;

    @Override
    public PageVO<CommentVO> pageComment(Long articleId, int pageNo) {
        // 1. 分页查询主表
        Page<Comment> page = Page.of(pageNo, 10);
        page = lambdaQuery().eq(Comment::getArticleId, articleId).page(page);

        // 2. 填充子表user信息
        // 2.1 查询子表user集合
        List<Comment> commentList = page.getRecords();
        Set<Integer> userIdSet = commentList.stream().map(Comment::getUserId).collect(Collectors.toSet());
        Map<Long, User> idUserMap = userService.mapByIds(userIdSet);
        // 2.2 主表信息和子表信息结合
        List<CommentVO> voList = commentList.stream().map(comment -> {
            CommentVO vo = new CommentVO();
            BeanUtil.copyProperties(comment, vo);
            User user = idUserMap.get(Long.valueOf(vo.getUserId()));
            if (Objects.nonNull(user)) {
                vo.setName(user.getUsername());
                vo.setAvatar(user.getAvatar());
            }
            return vo;
        }).toList();

        // 3. 封装返回
        PageVO<CommentVO> pageVO = new PageVO<>();
        pageVO.setList(voList);
        pageVO.setCurrent(page.getCurrent());
        pageVO.setSize(page.getSize());
        pageVO.setTotal(page.getTotal());
        pageVO.setPages(page.getPages());
        return pageVO;
    }
}
